package com.server.runtime;

import java.io.Serializable;
import java.util.ArrayList;

import combat.protocol.data.ChatEntry;
import combat.protocol.interfaces.ChatInt;

public class chatImpl implements ChatInt, Serializable {
	private static final long serialVersionUID = 1L;
	
	private static chatImpl instance = null;
	public int lastMessageID = 0;
	public ArrayList<ChatEntry> chats = new ArrayList<ChatEntry>();
	
	public final static chatImpl instance() {
		if(instance == null) {
			instance = new chatImpl();
		}		
		return instance;
	}
	
	public synchronized int getLastMessageID() {
		return this.lastMessageID;
	}

	public synchronized void setLastMessageID(int lastMessageID) {
		this.lastMessageID = lastMessageID;
	}

	public synchronized ArrayList<ChatEntry> getChats() {
		return this.chats;
	}
	
	public synchronized void setChats(ArrayList<ChatEntry> chats) {
		this.chats = chats;
	}

	public synchronized void sendChat(ChatEntry chat) {
		this.chats.add(chat);
	}

	public int getNewMessageID() {
		return lastMessageID++;
	}

	public synchronized ArrayList<ChatEntry> getNewChats(int lastKnownMessageID) {
		ArrayList<ChatEntry> newChats = new ArrayList<ChatEntry>();
		for(ChatEntry message : chats) {
			if(message.getMessageID() > lastKnownMessageID) {
				newChats.add(message);
			}
		}

		return newChats;
	}
	public void sendSystemMessage(String _message){
		ChatEntry systemMessage = new ChatEntry(
				getNewMessageID(), 
				"SYSTEM", 
				null, 
				_message
		);
		sendChat(systemMessage);
	}
}
